
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.Domain.Entities.Auditing;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Yozeev.BusinessLogic.Authorization;
using Yozeev.BusinessLogic.BoatBasic.ExcelDto;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.Common;
using Yozeev.IO.ExcelHelper;

namespace Yozeev.BusinessLogic
{
	/// <summary>
	/// Boat应用层服务的接口实现方法  
	///</summary>
	[AbpAuthorize]
	public class BoatAppService : YozeevAppServiceBase, IBoatAppService
    {
        private readonly IRepository<Boat, Guid> _entityRepository;

        private readonly IBoatManager _entityManager;

		private readonly IExcelHelper _excelHelper;

		private readonly IQueryHelper _queryHelper;

		/// <summary>
		/// 构造函数 
		///</summary>
		public BoatAppService(
        IRepository<Boat, Guid> entityRepository
        ,IBoatManager entityManager
			,IExcelHelper excelHelper
			, IQueryHelper queryHelper
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
			_excelHelper = excelHelper;
			_queryHelper = queryHelper;
        }


        /// <summary>
        /// 获取Boat的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>		
	   [HttpPost]
        public async Task<PagedResultDto<BoatListDto>> GetPaged(GetBoatsInput input)
		{
            var expression = _queryHelper.WhereExp<Boat>(input.queryData);
			if (AbpUserBase.AdminUserName != GetCurrentUser().UserName)
				expression = _queryHelper.SetWhereExp<Boat>(expression, GetViewTypeEnum<Boat>(), await GetBranchUser());
			var query = from entity in _entityRepository.GetAll().AsNoTracking()
                        .Where(expression)
                        select new
                        {
                            entity,
                            entity.Route,
                        };
            var list = new List<BoatListDto>();
            query.ToList().ForEach(temp =>
            {
                var _entity = temp.entity.MapTo<BoatListDto>();
                _entity.Route = temp.Route;
                list.Add(_entity);
            });
            // TODO:根据传入的参数添加过滤条件
            var count = list.Count();
			list = list.AsQueryable().OrderBy(input.Sorting)
					.PageBy(input)
					.ToList();
			return new PagedResultDto<BoatListDto>(count, list);
		}


		/// <summary>
		/// 通过指定id获取BoatListDto信息
		/// </summary>
		public async Task<BoatListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<BoatListDto>();
		}

		/// <summary>
		/// 获取编辑 Boat
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetBoatForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetBoatForEditOutput();
BoatEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<BoatEditDto>();

				//boatEditDto = ObjectMapper.Map<List<boatEditDto>>(entity);
			}
			else
			{
				editDto = new BoatEditDto();
			}

			output.Boat = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改Boat的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateBoatInput input)
		{

			if (input.Boat.Id.HasValue)
			{
				await Update(input.Boat);
			}
			else
			{
				await Create(input.Boat);
			}
		}


		/// <summary>
		/// 新增Boat
		/// </summary>
		protected virtual async Task<BoatEditDto> Create(BoatEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增
            // var entity = ObjectMapper.Map <Boat>(input);
            var entity=input.MapTo<Boat>();

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<BoatEditDto>();
		}

		/// <summary>
		/// 编辑Boat
		/// </summary>
		protected virtual async Task Update(BoatEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除Boat信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除Boat的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		/// <summary>
		/// 导出Boat为excel表,等待开发。
		/// </summary>
		/// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

		/// <summary>
		/// 从Excel表导入数据
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public async Task<ExcelResultDto> ImportBoat(IFormFile file)
		{
			string errorMessage = "";
			bool result;
			try
			{
				List<BoatExcelDto> data = _excelHelper.ReadToList<BoatExcelDto>(file);
				var boats = new List<Boat>();
				foreach (var dto in data)
				{
					boats.Add(new Boat
					{
						BoatName = dto.BoatName,
						BoatCode = dto.BoatCode,
						SeatNumber = dto.SeatNumber,
						AuditStatus = AuditStatusEnum.WaiteAudit,
						Leader = dto.Leader,
						RunStatus =RunStatusEnum.Running,
						LeaderMobile = dto.LeaderMobile,
						CreationTime = DateTime.Now,
						CreatorUserId = AbpSession.UserId,
						Id = Guid.NewGuid(),
					});
				}
				result= await _entityManager.BoatInsertAsync(boats);
			}
			catch (Exception e)
			{
				result= false;
				errorMessage = e.Message;
			}
			return new ExcelResultDto { Result = result, ErrorMessage = errorMessage };
		}
	}
}


